package com.bckj.fastboot.paid.biz.domain.pay.execution;

import com.bckj.fastboot.core.execution.Execution;
import com.bckj.fastboot.core.execution.ExecutionContext;
import com.bckj.fastboot.paid.api.constant.PayExecutionNames;
import com.bckj.fastboot.paid.biz.domain.pay.context.PayContext;
import com.bckj.fastboot.paid.biz.domain.pay.provider.PayGatewayProvider;
import com.bckj.fastboot.paid.api.entity.PayOrder;
import com.bckj.fastboot.paid.api.enums.PayStatusEnum;
import com.bckj.fastboot.paid.api.exceptions.PayException;
import com.bckj.fastboot.paid.biz.domain.pay.repo.PayOrderRepository;
import com.bckj.fastboot.paid.biz.infrastructure.convert.PayOrderConvert;
import com.bckj.fastboot.paid.api.model.PayRequest;
import com.bckj.fastboot.paid.api.model.PayResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class PayOrderCreateExecution implements Execution {

    private final PayOrderRepository payOrderRepository;
    private final PayOrderConvert payOrderConvert;

    @Override
    public String getName() {
        return PayExecutionNames.PAY_ORDER_CREATE;
    }

    @Override
    public void execute(ExecutionContext context) {
        PayContext ctx = (PayContext) context;
        PayRequest request = ctx.getRequest();
        PayOrder payOrder = payOrderConvert.toPayOrder(request);
        try {
            PayResponse payResponse = PayGatewayProvider.get(request.getPayWay()).pay(request);
            payOrder.setStatus(PayStatusEnum.PAYING.getCode());
            ctx.setResponse(payResponse);
        } catch (PayException e) {
            log.error("支付异常", e);
            payOrder.setStatus(PayStatusEnum.PAY_FAIL.getCode());
        }
        payOrderRepository.save(payOrder);
    }
}
